package com.baselibrary.manager;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;

import com.baselibrary.MessageBus;
import com.baselibrary.router.ActivityRouter;
import com.baselibrary.utils.ARouterUtils;
import com.baselibrary.utils.HKUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 *
 * @author zhanglijie
 * @date 2020年02月21日
 */
public class AppManager {

    /**
     * 结束指定的Activity
     */
    private static AppManager instance;

    private AppManager() {
    }

    /**
     * 单一实例
     */
    public static AppManager getAppManager() {
        if (instance == null) {
            synchronized (AppManager.class) {
                if (instance == null) {
                    instance = new AppManager();
                }
            }
        }
        return instance;
    }

    public List<Activity> getActivityStack() {
        return HKUtils.getActivityList();
    }


    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(@NonNull Activity activity) {
        activity.finish();
    }

    /**
     * 结束指定的 Activity
     *
     * @param clazz
     */
    public void finishActivity(@NonNull Class<? extends Activity> clazz) {
        List<Activity> activityList = HKUtils.getActivityList();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            activityList.forEach(activity -> {
                if (activity.getClass().equals(clazz)) {
                    activity.finish();
                }
            });
        } else {
            for (Activity activity : activityList) {
                if (activity.getClass().equals(clazz)) {
                    activity.finish();
                }
            }
        }
    }

    /**
     * 退栈到指定的 Activity
     *
     * @param activity
     */
    public void finishToActivity(@NonNull final Activity activity) {
        List<Activity> activityList = HKUtils.getActivityList();
        for (int i = activityList.size() - 1; i >= 0; i--) {
            Activity tempActivity = activityList.get(i);
            if (activity.equals(tempActivity)) {
                return;
            }
            finishActivity(tempActivity);
        }
    }

    /**
     * 除传入的 Activity 以外，全部清除
     *
     * @param clazz 要保留的 Activity
     */
    public void finishOtherActivity(@NonNull final Class<? extends Activity> clazz) {
        List<Activity> activityList = HKUtils.getActivityList();
        for (int i = activityList.size() - 1; i >= 0; i--) {
            Activity activity = activityList.get(i);
            if (!activity.getClass().equals(clazz)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 除传入的 Activity 以外，全部清除
     *
     * @param activity 要保留的 Activity
     */
    public void finishOtherActivity(@NonNull final Activity activity) {
        List<Activity> activityList = HKUtils.getActivityList();
        for (int i = activityList.size() - 1; i >= 0; i--) {
            Activity tempActivity = activityList.get(i);
            if (!tempActivity.equals(activity)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        List<Activity> activityList = HKUtils.getActivityList();
        for (int i = activityList.size() - 1; i >= 0; i--) {
            Activity tempActivity = activityList.get(i);
            tempActivity.finish();
        }
    }


    /**
     * 退出应用程序
     */
    public void appExit(Context context) {
        finishAllActivity();
    }

    public void getActPackageName(Activity activity) {
        ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);

        ActivityManager.RunningTaskInfo info = manager.getRunningTasks(1).get(0);

        String shortClassName = info.topActivity.getShortClassName(); //类名

        String className = info.topActivity.getClassName(); //完整类名

        String packageName = info.topActivity.getPackageName(); //包名

        Log.d("===========", "shortClassName: " + shortClassName);
        Log.d("===========", "className: " + className);
        Log.d("===========", "packageName: " + packageName);
    }


    public void reLoginEvent() {
        MessageBus.Builder builder = new MessageBus.Builder();
        MessageBus messageBus = builder
                .codeType(MessageBus.msgId_login_up)
                .build();
        EventBus.getDefault().postSticky(messageBus);
    }

    /**
     * 登录界面点击【返回】
     */
    public void loginOnBack() {
        MessageBus.Builder builder = new MessageBus.Builder();
        MessageBus messageBus = builder
                .codeType(MessageBus.msgId_login_onBack)
                .build();
        EventBus.getDefault().post(messageBus);
    }

    public boolean checkApplication(Activity activity, String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = activity.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public boolean isExistMainActivity(Context context, Class<?> activity) {
        Intent intent = new Intent(context, activity);
        ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
        boolean flag = false;
        if (cmpName != null) {// 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);//获取从栈顶开始往下查找的10个activity
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) {// 说明它已经启动了
                    flag = true;
                    break;//跳出循环，优化效率
                }
            }
        }
        return flag;//true 存在 falese 不存在

    }

    public void openLoginPage(String openAppointActName) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("openAppointActName", openAppointActName);
        ARouterUtils.jump(ActivityRouter.LOGIN.LOGIN_PAGE, hashMap);
    }

    public  void openLoginPage() {
        ARouterUtils.jump(ActivityRouter.LOGIN.LOGIN_PAGE);
    }

    public void openLoginPage(int flag) {
        ARouterUtils.jump(ActivityRouter.LOGIN.LOGIN_PAGE, flag);
    }

    public static String readLocalJson(Context context, String fileName) {
        String jsonString = "";
        String resultString = "";
        try {
            InputStream inputStream = context.getResources().getAssets().open(fileName);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            resultString = new String(buffer);
        } catch (Exception e) {
        }
        return resultString;
    }


    public static boolean isValidActivity(Activity activity) {
        if (!activity.isDestroyed() && !activity.isFinishing()) {
            return true;
        }
        return false;
    }
}
